import { call, put, takeLatest } from 'redux-saga/effects';
import { GET_BOOKS, booksIsAdmin, booksList, ISEXISTS_DIRNAME, GET_UPLOAD_TOKEN } from '../actions/books.action';
import Message from '../components/SimpleLayer/Message';
import API from '../services';
import { $$ } from '../modules/utils';
 
function showErr(content){
	Message.error({
		top:'6px',
		width:'300',
		content,
		delayAutoClose:2000,
		yes:false
	});
}
function* BooksList(action) {
   try {
      	const res = yield call(API.BooksList, action.data);
  		if (res.success) {
  			yield put(booksIsAdmin(res.isAdmin));
  			yield put(booksList(res.result));
		}else{
			showErr(res.result);
		}
   } catch (e) {
      	showErr(e.message);
   }
}

function* BooksSaga() {
  yield takeLatest(GET_BOOKS, BooksList);
}

export default BooksSaga;

export function* IsexistsDirname(){
	yield takeLatest(ISEXISTS_DIRNAME,function* (action){
		try{
			const res = yield call(API.IsExistsDirname,action.data);
			if (res.success) {
				showErr(res.result);
				document.querySelector('.dirname').setAttribute('data-value',1);
			};
		}catch(e){
			showErr(e.message);
		}
	})
}

export function* getUploadToken(){
	yield takeLatest(GET_UPLOAD_TOKEN, function* (action){
		try{
			const res = yield call(API.Login, action.data);
			if (res.success) {
				let utext = $$('.utext');
				var upswd=$$('.upswd');
				let utoken = $$('.utoken');
				let itoken = $$('.itoken');
				utext.className += ' itemout';
				setTimeout(() => {upswd.className += ' itemout'},150);
				utoken.value = res.result;
				itoken.className += ' itemin';
			}else{
				showErr(res.result)
			};
		}catch(e){
			showErr(e.message);
		}
	})
}